package com.yfjin.h264.tcrtc;


import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.FrameLayout;

import com.tencent.liteav.device.TXDeviceManager;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.yfjin.h264.tcrtc.config.UserSigGenerator;
import com.yfjin.h264.tcrtc.listener.CloudListenerDelegate;
import com.yfjin.h264.tcrtc.listener.RoomInfoCallback;

/**
 * @author jinyf
 */
public class RtcManager {

    private static final String TAG = "RtcManager";

    private RtcManager() {
    }

    public static volatile RtcManager INSTANCE;

    public static RtcManager INSTANCE() {
        if (INSTANCE == null) {
            synchronized (RtcManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new RtcManager();
                }
            }
        }
        return INSTANCE;
    }

    private RtcStatus mStatusCallback;

    private boolean mStarting = false;
    private TRTCCloud mTRTCCloud;
    private Params mParams;

    private TRTCCloudDef.TRTCVideoFrame mVideoFrame;
    private TRTCCloudDef.TRTCAudioFrame mAudioFrame;

    public boolean start(Context context, Params params, RtcStatus callback) {
        if (!paramsVaild(params)) {
            return false;
        }

        mStatusCallback=callback;
        mParams = params;
        if (mTRTCCloud != null) {
            stop(false);
        }

        initCould(context.getApplicationContext());
        initParams();
        mStarting = true;
        return mStarting;
    }

    private boolean paramsVaild(Params params) {

        if (TextUtils.isEmpty(params.mRobotId) || TextUtils.isEmpty(params.mRoomId)) {
            Log.e(TAG, "用户数据为空");
            return false;
        }

        if (TextUtils.isEmpty(params.mSecertKey) || params.mAppId <= 0) {
            Log.e(TAG, "App参数为空");
            return false;
        }

        return true;
    }

    public void stop(boolean needCallback) {
        mStarting = false;
        if (mTRTCCloud != null) {
            mTRTCCloud.stopAllRemoteView();
            mTRTCCloud.exitRoom();
            mTRTCCloud = null;
        }

        if (needCallback&&mStatusCallback!=null){
            mStatusCallback.roomClosed();
        }
    }

    public void stop() {
        stop(true);
    }


    public void sendMsg(byte[] var2) {
        if (!mStarting || mTRTCCloud == null) {
            return;
        }
        mTRTCCloud.sendCustomCmdMsg(1, var2, false, false);
    }

    public void sendVideoData(byte[] nv21, int width, int height) {

        if (!mStarting || mTRTCCloud == null) {
            return;
        }

        //0高清/其他：辅路
        if (mVideoFrame == null) {
            mVideoFrame = new TRTCCloudDef.TRTCVideoFrame();
        }
        mVideoFrame.pixelFormat = TRTCCloudDef.TRTC_VIDEO_PIXEL_FORMAT_NV21;
        mVideoFrame.bufferType = TRTCCloudDef.TRTC_VIDEO_BUFFER_TYPE_BYTE_ARRAY;
        mVideoFrame.data = nv21;
        mVideoFrame.width = width;
        mVideoFrame.height = height;
        mVideoFrame.timestamp = mTRTCCloud.generateCustomPTS();
        mTRTCCloud.sendCustomVideoData(TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, mVideoFrame);
    }

    public void sendAudioData(byte[] audio, int sampleRate, int channel) {
        if (!mStarting || mTRTCCloud == null) {
            return;
        }

        if (mAudioFrame == null) {
            mAudioFrame = new TRTCCloudDef.TRTCAudioFrame();
        }
        mAudioFrame.data = audio;
        mAudioFrame.sampleRate = sampleRate;
        mAudioFrame.channel = channel;
        mAudioFrame.timestamp = mTRTCCloud.generateCustomPTS();
        mTRTCCloud.sendCustomAudioData(mAudioFrame);
    }

    private void initCould(Context context) {
        mTRTCCloud = TRTCCloud.sharedInstance(context);

        CloudListenerDelegate delegate = new CloudListenerDelegate();
        delegate.setRoomInfoCallback(new RoomInfoCallback() {
            @Override
            public void onNoUser() {
                stop(true);
            }

            @Override
            public void onFpsInfo(int rtt) {
            }

            @Override
            public void onEnterResult(long result) {
                if (mStatusCallback != null) {
                    mStatusCallback.onEnterResult(result);
                }
            }

            @Override
            public void onError(long result) {
                stop(true);
            }
        });

        mTRTCCloud.setListener(delegate);
    }

    public void startRemoteView(String userId,FrameLayout viewContiner) {
        if (mStarting && mTRTCCloud != null && viewContiner != null) {
            TXCloudVideoView showView = new TXCloudVideoView(viewContiner.getContext());
            showView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            viewContiner.removeAllViews();
            viewContiner.addView(showView);
            mTRTCCloud.startRemoteView(userId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG,showView);
        }
    }


    private void initParams() {
        Log.i("223223","mParams.mUseCustomData:"+mParams.mUseCustomData);
        if (mParams.mUseCustomData) {
            mTRTCCloud.enableCustomAudioCapture(true);
//            mTRTCCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
            mTRTCCloud.enableCustomVideoCapture(TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, true);
        } else {
            mTRTCCloud.startLocalPreview(true, mParams.mLocalView);
            mTRTCCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
        }

        //--------------------------------------------
        TRTCCloudDef.TRTCVideoEncParam encParams = createEncParams();
        mTRTCCloud.setVideoEncoderParam(encParams);
        //--------------------------------------------
        TRTCCloudDef.TRTCParams masterParams = createParams();
//        mTRTCCloud.enterRoom(params, TRTCCloudDef.TRTC_APP_SCENE_LIVE);
        mTRTCCloud.enterRoom(masterParams, TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL);
        //--------------------------------------------
        mTRTCCloud.setNetworkQosParam(new TRTCCloudDef.TRTCNetworkQosParam());
        //--------------------------------------------
        TXDeviceManager deviceManager = mTRTCCloud.getDeviceManager();
        deviceManager.enableCameraAutoFocus(true);

//        deviceManager.setCameraFocusPosition(200,200);
        /*切换成后置摄像头*/
//        deviceManager.switchCamera(false);
    }

    private TRTCCloudDef.TRTCVideoEncParam createEncParams() {
        TRTCCloudDef.TRTCVideoEncParam encParams = new TRTCCloudDef.TRTCVideoEncParam();
        encParams.enableAdjustRes = false;
        encParams.videoResolution = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_1280_720;
        encParams.videoBitrate = 1800;
//        trtcVideoEncParam.videoResolution = TRTC_VIDEO_RESOLUTION_1920_1080;
//        trtcVideoEncParam.videoBitrate=3000;
        return encParams;
    }

    private TRTCCloudDef.TRTCParams createParams() {
        TRTCCloudDef.TRTCParams params = new TRTCCloudDef.TRTCParams();
        params.sdkAppId = mParams.mAppId;
        params.userId = mParams.mRobotId;
        params.strRoomId = mParams.mRoomId;
        params.userSig = UserSigGenerator.genUserSig(mParams.mAppId
                , mParams.mRobotId
                , mParams.mSecertKey
        );
        //主播角色
        params.role = TRTCCloudDef.TRTCRoleAnchor;
        return params;
    }


    public static class Params {

        private TXCloudVideoView mLocalView;
        private boolean mUseCustomData = true;


        public Params setLocalViewContiner(FrameLayout view) {
            TXCloudVideoView showView = new TXCloudVideoView(view.getContext());
            showView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            view.removeAllViews();
            view.addView(showView);
            this.mLocalView = showView;
            return this;
        }

        public Params useCustomData(boolean useCustomData) {
            this.mUseCustomData = useCustomData;
            return this;
        }

        //--------------------------------------------------------------

        private String mRoomId;
        private int mAppId;
        private String mSecertKey;

        private String mRobotId;

        public Params(String roomId, String robotId, int appId, String secertKey) {
            this.mRoomId = roomId;
            this.mRobotId = robotId;
            this.mAppId = appId;
            this.mSecertKey = secertKey;
        }
    }


}
